#include <malloc.h>
#include <assert.h>
#include "unionfind.h"



int find(int p){
    assert(id != NULL);
    assert(p > 0 && p < union_find_size);
    return id[p];
}


void initUnionFind(int size){
    union_find_size = size;
    id = (int*) malloc(size * sizeof(int));
    if(id == NULL){
        union_find_size = 0;
        return;
    }
}

void destoryUnionFind(){
    union_find_size = 0;
    free(id);
    id = NULL;
}

int isConnected(int p, int q){
    return find(p) == find(q);
}

void UnionElement(int p, int q){
    int pId = find(p);
    int qId = find(q);
    if(pId == qId){
        return;
    } else{
        int i;
        for (i = 0; i < union_find_size; i++) {
            if(id[i] == pId){
                id[i] = qId;
            }
        }
    }
}